<template>
  <div>
    <el-card style="margin: 20px 0">
      <CategorySelect @getCategoryInfo="getCategoryInfo" :show="!isShowTable"></CategorySelect>
    </el-card>
    <el-card>
      <!-- 属性值列表 -->
      <div v-show="isShowTable">
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!category3id"
          @click="addAttr"
          >添加属性</el-button
        >
        <el-table
          style="width: 100%; margin: 20px 0"
          :data="categoryInfoList"
          border
        >
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column
            prop="attrName"
            label="属性名称"
            width="150"
            align="center"
          >
          </el-table-column>
          <el-table-column
            prop="attrValueList"
            label="属性值列表"
            width="width"
            header-align="center"
          >
            <template slot-scope="scope">
              <el-tag
                type="success"
                v-for="(item, index) in scope.row.attrValueList"
                :key="item.id"
                style="margin: 3px 10px"
              >
                {{ item.valueName }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作" width="150" align="center">
            <template slot-scope="scope">
              <el-button
                type="warning"
                icon="el-icon-edit"
                size="mini"
                @click="updateAttr(scope.row)"
              ></el-button>
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteAttr(scope.row)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 添加属性||修改属性 -->
      <div v-show="!isShowTable">
        <el-form ref="form" :inline="true" label-width="80px" :model="attrInfo">
          <el-form-item label="属性名">
            <el-input
              placeholder="请输入属性名"
              v-model="attrInfo.attrName"
            ></el-input>
          </el-form-item>
        </el-form>
        <el-button
          type="primary"
          icon="el-icon-plus"
          :disabled="!attrInfo.attrName"
          @click="addAttrValue"
        >
          添加属性值
        </el-button>
        <el-button @click="isShowTable = true">取消</el-button>
        <el-table
          style="width: 100%; margin: 20px 0"
          border
          :data="attrInfo.attrValueList"
        >
          <el-table-column type="index" label="序号" width="80" align="center">
          </el-table-column>
          <el-table-column prop="prop" label="属性值名称">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.valueName"
                placeholder="请输入属性值名称"
                size="mini"
                v-if="scope.row.flag"
                @blur="toSpan(scope.row)"
                @keyup.native.enter="toSpan(scope.row)"
                :ref="scope.$index"
              >
              </el-input>
              <span
                v-else
                @click="toInput(scope.row, scope.$index)"
                style="display: block"
                >{{ scope.row.valueName }}</span
              >
            </template>
          </el-table-column>
          <el-table-column prop="prop" label="操作">
            <template slot-scope="scope">
              <el-button
                type="danger"
                icon="el-icon-delete"
                size="mini"
                @click="deleteAttrRow(scope.row, scope.$index)"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-button
          type="primary"
          @click="saveAttrInfo"
          :disabled="attrInfo.attrValueList.length < 1"
          >保存</el-button
        >
        <el-button @click="isShowTable = true">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script>
//按需引入lodash当中的深拷贝
import cloneDeep from "lodash/cloneDeep";
export default {
  name: "Arrt",
  data() {
    return {
      category1id: "",
      category2id: "",
      category3id: "",
      categoryInfoList: [],
      isShowTable: true,
      // flag: true, //控制属性值input和span来回切换，不宜放这里。
      attrInfo: {
        attrName: "",
        attrValueList: [],
        categoryId: 0,
        categoryLevel: 3,
      },
    };
  },
  methods: {
    // 三级联动子组件传递自定义事件
    getCategoryInfo({ category1id, category2id, category3id }) {
      this.category1id = category1id;
      this.category2id = category2id;
      this.category3id = category3id;
      this.getcategoryInfoList();
    },
    // 三级联动获取品牌信息
    async getcategoryInfoList() {
      const { category1id, category2id, category3id } = this;
      let result = await this.$API.attr.reqgetCategoryInfoList(
        category1id,
        category2id,
        category3id
      );
      if (result.code == 200) {
        this.categoryInfoList = result.data;
      }
    },
    // 添加属性值
    addAttrValue() {
      this.attrInfo.attrValueList.push({
        attrId: this.attrInfo.id,
        valueName: "",
        flag: true, // flag放这里控制着row
      });
      // 点击添加属性值自动聚焦
      this.$nextTick(() => {
        this.$refs[this.attrInfo.attrValueList.length - 1].focus();
      });
    },
    // 添加属性
    addAttr() {
      this.isShowTable = false;
      this.attrInfo = {
        attrName: "",
        attrValueList: [],
        categoryId: this.category3id,
        categoryLevel: 3,
      };
    },
    // 修改属性
    updateAttr(row) {
      this.isShowTable = false;
      // this.attrInfo = {...row}  //浅拷贝
      // lodash的深拷贝cloneDeep
      this.attrInfo = cloneDeep(row);
      // attrInfo.attrValueList此时没有flag属性
      this.attrInfo.attrValueList.forEach((item) => {
        // item.flag = false 手动添加flag，视图不会发生变化（flag不是响应式数据）
        //因为Vue无法探测普通的新增 property,这样书写的属性并非响应式属性(数据变化视图)
        //第一个参数:对象 第二个参数:添加新的响应式属性 第三参数:新的属性的属性值
        this.$set(item, "flag", false);
        // 总结：在vue中，数据没有双向绑定时使用set
      });
      console.log(this.attrInfo.attrValueList);
    },
    // 添加属性值的input失去焦点，切换为span
    toSpan(row) {
      // row是当前属性
      // 1、属性值不能为空,空格
      if (row.valueName.trim() == "") {
        this.$message({
          message: "请输入正确的属性值",
          type: "warning",
        });
        return;
      }
      // 2、属性值不能重复
      let isRepat = this.attrInfo.attrValueList.some((item) => {
        if (row != item) {
          return row.valueName == item.valueName;
        }
      });
      // 如果重复不能失去焦点
      if (isRepat) return;
      row.flag = false;
    },
    // 点击span切换为input，自动聚焦
    toInput(row, index) {
      row.flag = true;
      // 点击
      this.$nextTick(() => {
        this.$refs[index].focus();
      });
    },
    // 删除属性值
    deleteAttrRow(row, index) {
      this.$confirm("确认删除" + row.valueName + "?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$message({
            type: "success",
            message: "删除成功!",
          });
          this.attrInfo.attrValueList.splice(index, 1);
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 保存添加属性或修改属性
    async saveAttrInfo() {
      // 首先过滤需要传的参数attrInfo，包括空的属性值不保存、flag参数去除，不能带给服务器
      this.attrInfo.attrValueList = this.attrInfo.attrValueList.filter(
        (item) => {
          if (item.valueName != "") {
            delete item.flag;
            return true;
          }
        }
      );
      if (this.attrInfo.attrValueList.length > 0) {
        try {
          await this.$API.attr.reqsaveAttrInfo(this.attrInfo);
          // isShowTable: true, 弹窗提示，再次获取平台属性展示
          this.isShowTable = true;
          this.$message({ type: "success", message: "属性保存成功" });
          this.getcategoryInfoList();
        } catch (error) {
          this.$message({ type: "error", message: "error" });
        }
      }
    },
    // 删除属性
    deleteAttr(row){
       this.$confirm('此操作将永久删除该属性, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          // 发请求删除属性
          let res = await this.$API.attr.reqdeleteAttr(row.id)
          if(res.code == 200){
              console.log(res)
              this.$message({type:"success", message:"删除成功"})
              this.getcategoryInfoList();
            }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
  },
};
</script>

<style scoped>
</style>